package com.lepu.app.fun.grow;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.HttpRequest;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.utils.secure.EncodeMD5;
import com.core.lib.widget.CircularImageView;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.adapter.HotPhotoCommentAdapter;
import com.lepu.app.fun.grow.bean.HotPhoto;
import com.lepu.app.fun.grow.bean.HotPhotoComment;
import com.lepu.app.fun.grow.bean.HotPhotoImage;
import com.lepu.app.fun.grow.fragment.FragmentHotPhoto;
import com.lepu.app.fun.grow.play.PlayImageAutoActivity;
import com.lepu.app.fun.my.fragment.FragmentMyHotPhoto;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

public class GrowHotPhotoDetailActivity extends BaseFragmentActivity implements
		AsyncRequest, OnRefreshListener, OnLoadListener,
		OnTopbarNewLeftLayoutListener,OnTopbarNewRightButtonListener,OnEditorActionListener{

	private static final String REQUEST_DATA_DETAIL = "request_data_detail";
	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final String REQUEST_SEND_COMMENT = "request_send_comment";
	private static final String REQUEST_SEND_LIKE = "request_send_like";
	
	private static final String REQUEST_DELETE_TOPIC = "request_delete_topic";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	private static final int MSG_SEND_COMMENT_SUCCESS = 20;
	private static final int MSG_SEND_COMMENT_FAIL = 21;

	private static final int MSG_LIKE_SUCCESS = 30;
	private static final int MSG_LIKE_FAIL = 31;

	private static final int MSG_DOWNLOAD_IMAGE = 40;
	private static final int MSG_DOWNLOAD_IMAGE_FAIL = 41;

	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private HotPhotoCommentAdapter mDataAdapter = null;
	private ArrayList<HotPhotoComment> mDataArrayList = null;
	private int mCurrentPage = 1;

	private String mHotPhotoId = "0";

	private View mLikeView;
	private TextView mLikeTextView;

	private String mCurrentDate = null;

	private HotPhoto mHotPhoto = null;
	private int mCurrentDowloadIndex = 0;

	private TextView mDownloadProgressTextView = null;

	private boolean mDowoloading = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grow_hot_photo_detail_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mHandler.removeMessages(MSG_DOWNLOAD_IMAGE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint({ "InflateParams", "NewApi", "ResourceAsColor" })
	private void init() {

		Bundle data = getIntent().getExtras();
		if (data != null  && data.size() > 0) {
			mHotPhotoId = data.getString("HotPhotoId");
		}

		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("相册详情");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);
		
		LinearLayout commentLayout = (LinearLayout) findViewById(R.id.commentLayout);
		commentLayout.setVisibility(View.GONE);

		mGoogleRefreshLayout.setRefreshing(true);
		requestDetail();
	}
	
	@SuppressLint({ "ResourceAsColor", "InflateParams" })
	private void initData()
	{
		if(MyApplication.getInstance().checkIsLogin())
		{
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			if(mHotPhoto.UserID.equals(loginInfo.UserID))
			{
				CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
				topbar.setRightButton(R.drawable.icon_delete);
				topbar.setOnTopbarNewRightButtonListener(this);
			}
		}

		Button sendButton = (Button) findViewById(R.id.sendButton);
		sendButton.setOnClickListener(mViewOnClickListener);

		View view = LayoutInflater.from(this).inflate(
				R.layout.grow_hot_photo_detail_top, null);

		mDownloadProgressTextView = (TextView) view
				.findViewById(R.id.downloadProgressTextView);

		CircularImageView accountIconImageView = (CircularImageView) view
				.findViewById(R.id.accountIconImageView);
		// accountIconImageView.setImageBitmap(ImageUtilBase.getBitmapByResId(
		// this, R.drawable.default_icon_small));
		// if (!TextUtils.isEmpty(mHotPhoto.Avatar)) {
		// String fileName = EncodeMD5.getMd5(mHotPhoto.Avatar);
		// String filePath = SdLocal.getCacheImagePath(this, fileName);
		// String imageUrl = mHotPhoto.Avatar;
		//
		// BitmapManager.getInstance().loadBitmap(imageUrl, filePath,
		// accountIconImageView, true);
		// }
//		UniversalImageLoadTool.disPlay(mHotPhoto.Avatar, accountIconImageView,
//				R.drawable.app_ic_default_avatar);
		LoginUtil.loadSelfUserImage(this, accountIconImageView, mHotPhoto.Avatar);

		accountIconImageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginUtil.jumpUserInfo(GrowHotPhotoDetailActivity.this, mHotPhoto.UserID);
			}
		});
		
		TextView titleTextView = (TextView) view
				.findViewById(R.id.titleTextView);
		TextView timeTextView = (TextView) view.findViewById(R.id.timeTextView);
		ImageView coverImageView = (ImageView) view
				.findViewById(R.id.coverImageView);// ??????????
		ImageView playImageView = (ImageView) view
				.findViewById(R.id.playImageView);
		TextView bottomTitleTextView = (TextView) view
				.findViewById(R.id.bottomTitleTextView);

		mLikeTextView = (TextView) view.findViewById(R.id.likeCountTextView);
		mLikeView = (LinearLayout) view.findViewById(R.id.likeLayout);
		mLikeView.setOnClickListener(mViewOnClickListener);

		if (mHotPhoto.HasFavour != null && mHotPhoto.HasFavour.equals("1")) {
			mLikeView.setSelected(true);
		} else {
			mLikeView.setSelected(false);
		}

		titleTextView.setText(mHotPhoto.NickName);
		timeTextView.setText(DateUtilBase.friendly_time(mHotPhoto.CreateTime));
		bottomTitleTextView.setText(mHotPhoto.AlbumDescription);
		mLikeTextView.setText(mHotPhoto.FavourCount);

		playImageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (mDowoloading) {
					UIHelper.showToast(GrowHotPhotoDetailActivity.this,
							"下载中...");
					return;
				}
				// play
				boolean flag = dowloadPhoto();
				if (!flag) {
					UIHelper.showToast(GrowHotPhotoDetailActivity.this,
							"下载中...");
				}
			}
		});

		int width = UtilityBase.getWindowWidthHeight(this)[0];
		LayoutParams params = coverImageView.getLayoutParams();
		params.width = width;
		params.height = width * 9 / 16;
		coverImageView.setLayoutParams(params);

		// 下载状态
		ArrayList<HotPhotoImage> imageList = mHotPhoto.PhotoList;
		if (imageList != null && imageList.size() > 0) {
			boolean flag = true;
			for (int i = 0; i < imageList.size(); i++) {
				HotPhotoImage image = imageList.get(i);
				String fileName = EncodeMD5.getMd5(image.PhotoUrl);
				String filePath = SdLocal.getAlbumHotPath(
						GrowHotPhotoDetailActivity.this, mHotPhoto.AlbumID,
						fileName);

				if (!new File(filePath).exists()) {
					flag = false;
					break;
				}
			}

			if (flag) {
				mDownloadProgressTextView.setText("下载完成");
			}
		}

		// album cover
//		if (!TextUtils.isEmpty(mHotPhoto.AlbumCover)) {
//			// String fileName = EncodeMD5.getMd5(mHotPhoto.AlbumCover);
//			// String filePath = SdLocal.getCacheImagePath(this, fileName);
//			String imageUrl = mHotPhoto.AlbumCover;
//
//			// BitmapManager.getInstance().loadBitmap(imageUrl, filePath,
//			// coverImageView, true);
//		}
		UniversalImageLoadTool.disPlay(mHotPhoto.AlbumCover, coverImageView,
				R.drawable.album_cover_default);

		mDataListView.addHeaderView(view);
		
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		contentEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(2000) });

		mGoogleRefreshLayout.setRefreshing(true);
		request(false);
		
		mDataListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				UtilityBase.closeSoftInput(GrowHotPhotoDetailActivity.this);
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				
			}
		});
		mDataListView
		.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		
		contentEditText.setOnEditorActionListener(this);
	}

	private boolean dowloadPhoto() {
		boolean flag = true;
		final ArrayList<HotPhotoImage> imageList = mHotPhoto.PhotoList;

		if (imageList != null && imageList.size() > 0) {
			for (int i = 0; i < imageList.size(); i++) {
				HotPhotoImage image = imageList.get(i);
				String fileName = EncodeMD5.getMd5(image.PhotoUrl);
				String filePath = SdLocal.getAlbumHotPath(
						GrowHotPhotoDetailActivity.this, mHotPhoto.AlbumID,
						fileName);

				if (!new File(filePath).exists()) {
					flag = false;
					break;
				}
			}

			if (flag) {
				mDowoloading = false;
				playPhoto();
			} else {
				if (mCurrentDowloadIndex <= imageList.size() - 1) {
					mDowoloading = true;
					new Thread(new Runnable() {

						@Override
						public void run() {

							HotPhotoImage image = imageList
									.get(mCurrentDowloadIndex);
							String fileName = EncodeMD5.getMd5(image.PhotoUrl);
							String filePath = SdLocal.getAlbumHotPath(
									GrowHotPhotoDetailActivity.this,
									mHotPhoto.AlbumID, fileName);

							boolean flag = false;
							if (!new File(filePath).exists()) {
								flag = HttpRequest.downloadFile(image.PhotoUrl,
										filePath);
							}

							if(flag)
							{
								mHandler.sendEmptyMessage(MSG_DOWNLOAD_IMAGE);
							}else{
								mHandler.sendEmptyMessage(MSG_DOWNLOAD_IMAGE_FAIL);
							}
							
						}
					}).start();
				} else {
					playPhoto();
				}
			}
		} else {
			UIHelper.showToast(this, "没有可下载的图片");
		}

		return flag;
	}

	private void playPhoto() {
		Intent intent = new Intent(this, PlayImageAutoActivity.class);
		if (mHotPhoto.PhotoList != null && mHotPhoto.PhotoList.size() > 0) {
			String[] titleArray = new String[mHotPhoto.PhotoList.size()];
			for (int i = 0; i < mHotPhoto.PhotoList.size(); i++) {
				titleArray[i] = mHotPhoto.PhotoList.get(i).PhotoDescription;
				//titleArray[i] = new String(EncodeBase64.decode(mHotPhoto.PhotoList.get(i).PhotoDescription));
			}
			intent.putExtra("titleArray", titleArray);
		}

		intent.putExtra("IsPlayNet", true);
		intent.putExtra("AlbumId", mHotPhotoId);
		startActivity(intent, true);
	}
	
	public void requestDetail() {

		String url = Setting.getHotPhotoDetailUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);

			params.put("AlbumID", mHotPhotoId);
		} catch (Exception e) {
		}
		map.put("ht", params);
		
		ApiClient.http_post_main(url, map, null, this, REQUEST_DATA_DETAIL, true,false,true);
	}

	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			mCurrentDate = DateUtilBase.stringFromDate(new Date(),
					DateUtilBase.DATE_ALL_ALL);
			request = REQUEST_DATA;
			mCurrentPage = page;
		}
		String url = Setting.getCommentsHotPhotoUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);

			params.put("HotAlbumID", mHotPhotoId);

			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false,true);
	}
	
	public void requestDeleteTopic() {
		String url = Setting.getDeleteHotPhotoUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("ShareAlbumIDList", mHotPhoto.AlbumID);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_DELETE_TOPIC,
				false);
	}
	
	private void sendContent()
	{
		boolean flag = MainTabActivity
				.jumpLogin(GrowHotPhotoDetailActivity.this);
		if (flag) {
			return;
		}

		EditText editText = (EditText) findViewById(R.id.contentEditText);
		String content = editText.getText().toString().trim();
		if (TextUtils.isEmpty(content)) {
			UIHelper.showToast(GrowHotPhotoDetailActivity.this,
					"亲，请先输入评论内容");
			return;
		}
		
		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		String url = Setting.getPubCommentHotPhotoUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("AlbumID", mHotPhotoId);
			params.put("ReplyContent", content);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post(url, map, null,
				GrowHotPhotoDetailActivity.this, REQUEST_SEND_COMMENT,
				true);
	}

	View.OnClickListener mViewOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

			switch (v.getId()) {
			case R.id.sendButton:

				sendContent();
				break;
			case R.id.likeLayout:

				boolean flag2 = MainTabActivity
						.jumpLogin(GrowHotPhotoDetailActivity.this);
				if (flag2) {
					return;
				}

				String optUrl = "";
				boolean isSelected = mLikeView.isSelected();
				if (!isSelected) {
					// 赞
					optUrl = Setting.getLikeHotPhotoUrl();
				} else {
					// 取消赞
					optUrl = Setting.getCancelLikeHotPhotoUrl();
				}

				Map<String, Object> optMap = new HashMap<String, Object>();
				JSONObject json = new JSONObject();
				try {
					json.put("DeviceID", Setting.DEVICEID);
					json.put("ApplicationID", Setting.APPLICATIONID);
					json.put("UserID", loginInfo.UserID);
					json.put("LoginToken", loginInfo.LoginToken);

					json.put("AlbumID", mHotPhotoId);
				} catch (Exception e) {
				}
				optMap.put("ht", json);

				//showProgressDialog();
				ApiClient.http_post(optUrl, optMap, null,
						GrowHotPhotoDetailActivity.this, REQUEST_SEND_LIKE,
						false);

				break;
			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressLint("DefaultLocale")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<HotPhotoComment> dataList = (ArrayList<HotPhotoComment>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mDataArrayList = dataList;
				} else {
					// UIHelper.showToast(GrowHotPhotoDetailActivity.this,
					// R.string.no_data);
				}

				if (mDataArrayList == null) {
					mDataArrayList = new ArrayList<HotPhotoComment>();
				}

				mDataAdapter = new HotPhotoCommentAdapter(
						GrowHotPhotoDetailActivity.this, mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				
				LinearLayout commentLayout = (LinearLayout) findViewById(R.id.commentLayout);
				commentLayout.setVisibility(View.VISIBLE);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				break;
			case MSG_DATA_MORE_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<HotPhoto> dataMoreList = (ArrayList<HotPhoto>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(GrowHotPhotoDetailActivity.this,
							R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_SEND_COMMENT_SUCCESS:

				hideProgressDialog();

				EditText editText = (EditText) findViewById(R.id.contentEditText);
				editText.setText("");

				HotPhotoComment comment = (HotPhotoComment) msg.obj;
				//comment.UserAvatar = Setting.getImageUrl(MyApplication.getInstance().getLoginInfo().Avatar);
				mDataArrayList.add(0, comment);
				mDataAdapter.notifyDataSetChanged();
				mDataListView.setSelection(1);

				break;
			case MSG_SEND_COMMENT_FAIL:

				hideProgressDialog();
				break;
			case MSG_LIKE_SUCCESS:

				//hideProgressDialog();
				FragmentHotPhoto instance = FragmentHotPhoto.getInstance();
				if(instance != null)
				{
					if (mLikeView.isSelected()) {
						instance.updateSelectedItem("0",
								msg.arg1);
					} else {
						instance.updateSelectedItem("1",
								msg.arg1);
					}
				}

				mLikeView.setSelected(!mLikeView.isSelected());

				mLikeTextView.setText(String.valueOf(msg.arg1));
//				if(MotherMessageActivity.getInstance() != null){
//					//GrowMessageActivity.getInstance().mGoogleRefreshLayout.setRefreshing(false);
//					//GrowMessageActivity.getInstance().request(false);
//				}
				break;
			case MSG_LIKE_FAIL:

				//hideProgressDialog();
				break;
			case MSG_DOWNLOAD_IMAGE:

				mCurrentDowloadIndex++;

				String toast = String.format("%d / %d", mCurrentDowloadIndex,
						mHotPhoto.PhotoList.size());
				LogUtilBase.LogD(null, toast);

				mDownloadProgressTextView.setText(toast);

				// update ui
				dowloadPhoto();
				break;
			case MSG_DOWNLOAD_IMAGE_FAIL:
				
				UIHelper.showToast(GrowHotPhotoDetailActivity.this, "下载失败");
				mDownloadProgressTextView.setText("下载失败");
				
				mDowoloading = false;
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		
		if(mHotPhoto != null && !TextUtils.isEmpty(mHotPhoto.UserID))
		{
			request(true);
		}else{
			//详情获取失败，重新获取
			requestDetail();
		}
	}

	@Override
	public void onRefresh() {
		
		if(mHotPhoto != null && !TextUtils.isEmpty(mHotPhoto.UserID))
		{
			request(false);
		}else{
			//详情获取失败，重新获取
			requestDetail();
		}
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			ArrayList<HotPhotoComment> dataArraylist = HotPhotoComment
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			// 解析json data more
			ArrayList<HotPhotoComment> dataMoreArraylist = HotPhotoComment
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					HotPhotoComment item = dataMoreArraylist.get(i);
					mDataArrayList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_SEND_COMMENT)) {

			HotPhotoComment comment = HotPhotoComment
					.parseJsonSimpleData((String) data);

			if (comment != null) {
				Message commentMsg = mHandler.obtainMessage();
				commentMsg.obj = comment;
				commentMsg.what = MSG_SEND_COMMENT_SUCCESS;
				mHandler.sendMessage(commentMsg);
			} else {
				mHandler.sendEmptyMessage(MSG_SEND_COMMENT_FAIL);
			}
		} else if (object.equals(REQUEST_SEND_LIKE)) {
			String result = (String) data;
			int code = 0;
			int count = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");

				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");
				count = obj2.optInt("FavourCount");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {
				Message msg = mHandler.obtainMessage();
				msg.what = MSG_LIKE_SUCCESS;
				msg.arg1 = count;
				mHandler.sendMessage(msg);
			} else {
				mHandler.sendEmptyMessage(MSG_LIKE_FAIL);
			}
		}else if (object.equals(REQUEST_DELETE_TOPIC)) {
			// main thread
			hideProgressDialog();

			FragmentHotPhoto instance = FragmentHotPhoto.getInstance();
			if(instance != null)
			{
				instance.deleteIndex();
			}
			
			//我的发表的热门相册
			FragmentMyHotPhoto instance2 = FragmentMyHotPhoto.getInstance();
			if(instance2 != null)
			{
				instance2.deleteIndex();
			}

			finish(true);
		}else if(object.equals(REQUEST_DATA_DETAIL))
		{
			// main thread
			mGoogleRefreshLayout.setRefreshing(false);
			
			mHotPhoto = HotPhoto.parseJsonSimpleData((String) data);
			initData();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} else if (object.equals(REQUEST_SEND_COMMENT)) {
			mHandler.sendEmptyMessage(MSG_SEND_COMMENT_FAIL);
		} else if (object.equals(REQUEST_SEND_LIKE)) {
			mHandler.sendEmptyMessage(MSG_LIKE_FAIL);
		}else if (object.equals(REQUEST_DELETE_TOPIC)) {
			// main thread

			hideProgressDialog();
		}else if(object.equals(REQUEST_DATA_DETAIL))
		{
			// main thread
			mGoogleRefreshLayout.setRefreshing(false);
		}
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}
	
	@Override
	public void onTopbarRightButtonSelected() {
		MyDialog dialog = new MyDialog(this)
				.setMessage("您确认要删除这条热门相册吗?")
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						requestDeleteTopic();
					}
				})
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}
	
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEND:
			
			sendContent();
			break;
		}
		return false;
	}

}
